package com.ruoyi.common.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

public class LocalDateTimeTypeHandler extends BaseTypeHandler<Date> {
        @Override
        public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException {
            Instant instant = parameter.toInstant();
            ZoneId zoneId = ZoneId.of ( "Asia/Shanghai" );//使用北京时区
            ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
            LocalDate localDate = zdt.toLocalDate();
            java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );
            ps.setDate(i, sqlDate);
        }
        @Override
        public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
            String value = rs.getString(columnName);
            return convertToDate(value);
        }
        @Override
        public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
            String value = rs.getString(columnIndex);
            return convertToDate(value);
        }
        @Override
        public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
            String value = cs.getString(columnIndex);
            return convertToDate(value);
        }
        private Date convertToDate(String strDate){
            SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
            try {
                return sdf.parse(strDate);
            }catch(Exception ex){
                ex.printStackTrace();
            }
            return  null;
        }
    }